import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Card, Select, Radio, Checkbox, DatePicker, message, Modal, Table, InputNumber } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import moment from 'moment'
import GoodsListModal from './subComp/goodsListModal'
import { getCouponClassify, addNewCoupon } from '@/services/marketCenter/YHQ'
import RenderButtom from '@/components/RenderButton'
const { RangePicker } = DatePicker
const dateFormat = 'YYYY-MM-DD HH:mm:ss'
import {router} from 'umi'

const AddCoupon = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const { TextArea } = Input
  const [currType, setCurrType] = useState(1)
  const [isAllGoods, setIsAllGoods] = useState(0)
  const [modalVisible, setModalVisible] = useState(false)
  const [goodsList, setGoodsList] = useState([])
  const [goodsListCopy, setGoodsListCopy] = useState([])
  const [couponClassify, setCuponClassify] = useState([])
  const [isBeLimit, setIsBeLimit] = useState(false)
  const [useValidDay, setUseValidDay] = useState(null)
  const [validityTimeDisable, setValidityTimeDisable] = useState(true)

  const YHQ_type = [
    {id: 1, name: "代金券"},
    {id: 2, name: "折扣券"},
    {id: 3, name: "礼品券"},
  ]
  const formItemLay_1 = {
    labelCol: { span: 4 },
    wrapperCol: { span: 10 },
  }
  const formItemLay_2 = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  }


  useEffect(() => {
    init()
  }, [])
  // const _getCouponClassify = async () => {
  //   const r2 = await addNewCoupon({...values})
  // }
  const init = async () => {
    const r_1 = await getCouponClassify({pageNo: 1, pageSize: 99999, status: 1})
    setCuponClassify(r_1.data)
  }

  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 1:
        form.validateFields(async (err, values) => {
          console.log(values)
          const r3 = await addNewCoupon({
            ...values,
            effectiveTime: moment(values.dateTime_1[0]).format(dateFormat),
            expirationTime: moment(values.dateTime_1[1]).format(dateFormat),
            receiveSatrtTime: moment(values.dateTime_2[0]).format(dateFormat),
            receiveEndTime: moment(values.dateTime_2[1]).format(dateFormat),
            useValidDay: useValidDay
          })
          if (r3.resultCode == 1000) {
            message.success('优惠券创建成功!')
            router.push({
              pathname: '/marketCenter/coupon/couponManage'
            })
          }
        })
        break;
      default:
        break;
    }
  }


  const columns_1 = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (v, r, i) => {
        return (<span>{i+1}</span>  )
      }
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      render: (v, r, i) => {
        return (
          <img src={v} alt="" style={{width: '35px', height: '35px'}}/>
        )
      }
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '商品编号',
      dataIndex: 'goodsCode',
    },
    {
      title: '价格（元）',
      dataIndex: 'shopPrice',
    },
    {
      title: '库存',
      dataIndex: 'goodsStockNum',
    },
    {
      title: '操作',
      render: (record) => {
        return (<Button type="danger" onClick={() => handleRemove(record.id)}>删除</Button>)
      }
    },
  ]
  const handleCurrType = (value) => setCurrType(value)
  const handleSetModalVisible = () => setModalVisible(true)
  const handleOk = () => {
    setModalVisible(false)
    setGoodsList(goodsListCopy)
  }
  const handleCancel = () => setModalVisible(false)
  const handleSetIsAllGoods = (e) => {
    setIsAllGoods(e.target.value)
  }
  const handleRemove = (id) => {
    let result = goodsList.filter(item => item.id !== id)
    setGoodsList(result)
  }

  const distinct = (goodsList, Rows, rowKeys) => {
    let arr = goodsList.concat(Rows)
    let result = []
    let obj = {}
    for (let item of arr) {
      if (!obj[item.id]) {
        result.push(item)
        obj[item.id] = true
      }

    }
    return result.filter(r => rowKeys.indexOf(r.id) > -1)
  }

  const handleSelectedGoods = (rowKeys, Rows) => {
    let result = distinct(goodsList, Rows, rowKeys)
    setGoodsListCopy(result)
  }
  const handleUseValidDay = (v) => {
    setUseValidDay(v)
  }

  const handleValidityTimeType = (e) => {
    let flag = e.target.value == 0 ? true : false
    setValidityTimeDisable(flag)
  }
  const handleLimitType = (e) => {
    setIsBeLimit(e.target.value)
  }
  return (<PageHeaderWrapper>
    <Form layout={formLayout}>
      <Card size="small" title="优惠券信息" bordered={false}>
        <Form.Item label={`优惠券类型：`} {...formItemLay_1}>
          {getFieldDecorator('couponType', {
            rules: [{
              required: true,
              message: '必须选择一种优惠券类型',
            }],
            initialValue: 1,
          })(<Select onChange={handleCurrType}>
            {YHQ_type.map((r, index) => <Select.Option key={index} value={r.id}>{r.name}</Select.Option>)}
          </Select>)}
        </Form.Item>
        <Form.Item label={`优惠券名称：`} {...formItemLay_1}>
          {getFieldDecorator('couponName', {
            rules: [{
              required: true,
              message: '必须输入优惠券名称',
            }],
          })(<Input placeholder="输入优惠券名称" />)}
        </Form.Item>
        { currType == 1 && <Form.Item label={`面值：`} {...formItemLay_1}>
          {getFieldDecorator('denomination', {
            rules: [{
              required: true,
              message: '必须输入面值',
            }],
            initialValue: 0,
          })(<Input />)}
        </Form.Item>}
        { currType == 2 && <Form.Item label={`折扣率：`} {...formItemLay_1}>
          {getFieldDecorator('discountRate', {
            rules: [{
              required: true,
              message: '必须输入折扣率',
            }],
            initialValue: 0,
          })(<Input />)}
        </Form.Item>}
        <Form.Item label={`优惠券分类：`} {...formItemLay_1}>
          {getFieldDecorator('sysClassId', {
            rules: [{
              required: true,
              message: '必须选择分类',
            }]
          })(<Select>
            {couponClassify.map((r, index) => <Select.Option key={index} value={r.id}>{r.className}</Select.Option>)}
          </Select>)}
        </Form.Item>
        { currType != 3 && <Form.Item label={`使用条件：`} {...formItemLay_1}>
          {getFieldDecorator('limitType', {
            initialValue: 0,
          })(<Radio.Group onChange={handleLimitType}>
            <Radio value={0}>无限制</Radio>
            <Radio value={1}>满金额使用</Radio>
          </Radio.Group>)}
        </Form.Item>}
        { isBeLimit && <Form.Item label={`满`} {...formItemLay_1}>
          {getFieldDecorator('limit_price', {
            initialValue: 0,
          })(<Input  style={{width: '70px'}}/>)} 元可使用
        </Form.Item>}
        { currType != 3 && <Form.Item label={`发放类型：`} {...formItemLay_1}>
          {getFieldDecorator('sendType', {
            rules: [{
              required: true,
              message: '必须选择发放类型',
            }],
            initialValue: 0,
          })(<Radio.Group>
            <Radio value={0}>系统发放</Radio>
            <Radio value={1}>用户领取</Radio>
          </Radio.Group>)}
        </Form.Item>}
        <Form.Item label={`有效期类型`} {...formItemLay_1}>
          {getFieldDecorator('validityTimeType', {
            rules: [{
              required: true,
              message: '必须选择有效期类型',
            }],
            initialValue: 0,
          })(<Radio.Group onChange={handleValidityTimeType}>
            <Radio value={0}>固定时间</Radio>
            <Radio value={1}>领取后<InputNumber disabled={validityTimeDisable} min={0} defaultValue={0} onChange={handleUseValidDay}/>天有效</Radio>
          </Radio.Group>)}
        </Form.Item>
        {validityTimeDisable && <Form.Item label="券使用有效时间" {...formItemLay_1}>
          {getFieldDecorator(`dateTime_1`, {
            defaultValue: [moment(), moment()]
          })
            (<RangePicker format={dateFormat} />)}
        </Form.Item>}
        <Form.Item label="券的可领取时间" {...formItemLay_1}>
          {getFieldDecorator(`dateTime_2`, {
            defaultValue: [moment(), moment()]
          })
            (<RangePicker format={dateFormat} />)}
        </Form.Item>
        <Form.Item label={`使用说明：`} {...formItemLay_1}>
          {getFieldDecorator(`couponUseInstruction`, {})(<TextArea
          placeholder="使用说明"
        />)}
        </Form.Item>
        <Form.Item label={`发放总量：`} {...formItemLay_1}>
          {getFieldDecorator('lssuedQty', {
            rules: [{
              required: true,
              message: '必须输入面值',
            }],
            initialValue: 0,
          })(<Input />)}
        </Form.Item>
        <Form.Item label={`单日限领张数：`} {...formItemLay_1}>
          {getFieldDecorator('receiveLimitDay', {
            rules: [{
              required: true,
              message: '单日限领张数必须输入',
            }],
            initialValue: 0,
          })(<Input />)}
        </Form.Item>
        <Form.Item label={`总限领张数：`} {...formItemLay_1}>
          {getFieldDecorator('receiveLimitTotal', {
            rules: [{
              required: true,
              message: '总限领张数必须输入',
            }],
            initialValue: 0,
          })(<Input />)}
        </Form.Item>
        { currType != 3 && <Form.Item label={`是否可叠加使用：`} {...formItemLay_1}>
          {getFieldDecorator(`canSuperimposed`, {
            initialValue: 0,
          })(<Radio.Group>
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </Radio.Group>)}
        </Form.Item>}
      </Card>
      <Card size="small" title="使用设置" bordered={false} style={{ marginTop: '15px' }}>
        <Form.Item label={`可用商品`} {...formItemLay_1}>
          {getFieldDecorator(`goodsScope`, {
            initialValue: 0,
          })(<Radio.Group onChange={handleSetIsAllGoods}>
            <Radio value={0}>全部商品</Radio>
            <Radio value={1}>指定商品</Radio>
          </Radio.Group>)}
        </Form.Item>
        <Form.Item label={`非原价商品是否可用`} {...formItemLay_1}>
          {getFieldDecorator(`usableGoods`, {
            initialValue: 0,
          })(<Radio.Group>
            <Radio value={0}>不可用</Radio>
            <Radio value={1}>可用</Radio>
          </Radio.Group>)}
        </Form.Item>
        { isAllGoods == 1 && <Button type="primary" icon="add" onClick={handleSetModalVisible}>添加商品</Button> }
        { isAllGoods == 1 && <Table size="small" rowKey={record => record.id}  columns={columns_1} dataSource={goodsList}/> }
      </Card>
    </Form>
    <RenderButtom click={handleBtn} />
    <Modal
      width={1200}
      title={"选择商品"}
      visible={modalVisible}
      onOk={handleOk}
      onCancel={handleCancel}>
        <GoodsListModal selectedGoods={handleSelectedGoods} />
    </Modal>
  </PageHeaderWrapper>)
}

export default Form.create()(AddCoupon)
